namespace Roids.SL
{
    using System.Collections.Generic;
    using System.Linq;
    using Framework;
    using Microsoft.Xna.Framework;
    using Microsoft.Xna.Framework.Graphics;

    public class AsteroidSet : ISceneComponent
    {
        private const int ASTEROID_COUNT = 15;
        public static readonly int DefaultSize = 128;
        private readonly IList<Asteroid> _asteroids = new List<Asteroid>(ASTEROID_COUNT);
        private readonly Game _game;
        private readonly SpriteSheet _spriteMap;
        private Texture2D _texture;

        public AsteroidSet(Game game)
        {
            _game = game;
            _spriteMap = new SpriteSheet(128, 128, 1280, 512);
            _spriteMap.InitializeScenes(new[] {38});
        }

        public IList<Asteroid> Items
        {
            get { return _asteroids; }
        }

        public void LoadContent()
        {
            _texture = _game.Content.Load<Texture2D>(@"Sprites\rock1");
        }

        public void Update(GameTime gameTime)
        {
            foreach (var asteroid in _asteroids)
            {
                asteroid.Update(gameTime);
            }
        }

        public void Draw(GameTime gameTime, SpriteBatch batch)
        {
            foreach (var asteroid in _asteroids)
            {
                var src = new Rectangle(0, 0, 128, 128);
                batch.Draw(_texture, asteroid.Position, src, Color.White);
            }
        }

        public void StartLevel()
        {
            var w = _game.Window.ClientBounds.Width;
            var h = _game.Window.ClientBounds.Height;

            for (int i = 0; i < ASTEROID_COUNT; i++)
            {
                var rock = new Asteroid(_game, DefaultSize)
                               {
                                   Position = Randomizer.Create(w, h),
                                   Velocity = Randomizer.GetVector()
                               };
                _asteroids.Add(rock);
            }
        }

        public void Clean()
        {
            foreach (var asteroid in _asteroids.ToList())
            {
                if (asteroid.ReadyToRemove)
                    _asteroids.Remove(asteroid);
            }
        }
    }
}